package com.example.zheng.qq.activity;



import android.Manifest;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.provider.Settings;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.example.zheng.qq.R;
import com.example.zheng.qq.adapter.Card;
import com.example.zheng.qq.adapter.PageAdapter;
import com.example.zheng.qq.controller.PagerScroller;
import com.example.zheng.qq.controller.TogglePicture;
import com.example.zheng.qq.entity.Information;
import com.example.zheng.qq.entity.UseName;
import com.example.zheng.qq.fragment.MainDrawer;
import com.example.zheng.qq.fragment.StartDrawer;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class MainActivity extends AppCompatActivity{
    public UseName useName;
    public static final int CHOOSE_PHOTO=2;
    private StartDrawer fragment;
    private MainDrawer fragment1;
    private Uri imageUri;
    private File image;
    private ImageView resouce;
    private List<Information> list=new ArrayList<>();
    private SwipeRefreshLayout refresh;
    private Card card;
    private RecyclerView recyclerView;
    private List<ImageView> imageList=new ArrayList<>();
    private ViewPager viewPager;
    private PageAdapter pageAdapter;
    private Thread thread;
    private ImageView resourceView;
    private int count=0;
    private DrawerLayout drawerLayout;
    private RelativeLayout relativeLayout;
    private Boolean isExit=false;
    private boolean mHasFocus;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        useName= (UseName) getIntent().getSerializableExtra("user");
        StartDrawer.init(useName);
        MainDrawer.init(useName);
        fragment=new StartDrawer();
        fragment1=new MainDrawer();
        setContentView(R.layout.activity_main);


        FragmentManager fragmentManager=getSupportFragmentManager();
        FragmentTransaction transaction=fragmentManager.beginTransaction();
        transaction.replace(R.id.start_drawer,fragment);
        transaction.replace(R.id.main_drawer,fragment1);
        transaction.commit();
        init();
        recyclerView=(RecyclerView)findViewById(R.id.recycler);
        GridLayoutManager layoutManager=new GridLayoutManager(this,2);
        recyclerView.setLayoutManager(layoutManager);
        card=new Card(list);

        //给ViewPager绑定适配器，加载图片进去，并实现图片可以被滑动
        pageAdapter=new PageAdapter(imageList);
        viewPager=(ViewPager)findViewById(R.id.viewpager);
        viewPager.setAdapter(pageAdapter);
        viewPager.setPageTransformer(true,new TogglePicture());
        PagerScroller pager=new PagerScroller(this);
        pager.setScrollSpeed(3500);
        pager.refrashPageView(viewPager);
        refsh();

        //给卡片View绑定适配器
        recyclerView.setAdapter(card);
        //获取到刷新的控件，并帮顶刷新的点击事件，实现刷新操作
        refresh=(SwipeRefreshLayout)findViewById(R.id.refresh);
        refresh.setColorSchemeResources(R.color.colorPrimary);
        refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refreshList();
            }


        });
        RelativeLayout relativeLayout=(RelativeLayout)findViewById(R.id.main_drawer);
        resourceView=(ImageView) LayoutInflater.from(this).inflate(R.layout.main_drawer,relativeLayout,false).findViewById(R.id.resource1);

//        resouce= (ImageView) findViewById(R.id.images);
    }


    @Override
    protected void onResume() {
        super.onResume();

    }

    /*@Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        Log.d("error", "onWindowFocusChanged= " + hasFocus);

        mHasFocus = hasFocus;
        // tell the phonewindowmanager to pass the media key to user
        Settings.System.putInt(getApplicationContext().getContentResolver(),
                "power_key_to_mmitest", mHasFocus ? 1 : 0);

        /// bird: BUG #7864,recent key on navibar as KEYCODE_APP_SWITCH for mmitest,chengting,@20151104 {
        Settings.System.putInt(getContentResolver(), "bd_sys.app_switch_key_to_app", mHasFocus ? 1 : 0);
        /// @}
        Settings.System.putInt(getContentResolver(), "menu_key_to_mmitest",mHasFocus ? 1 : 0);//add by liuzhiling for mmitest 20160727
        Log.d("error", "onWindowFocusChanged1= " + hasFocus);
    }
*/


    //实现ViewPager里面的图片自动切换
    private void refsh() {
         thread=new Thread() {
            @Override
            public void run() {
                try {
                    while(true) {
                        sleep(4000);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                viewPager.setCurrentItem((viewPager.getCurrentItem()+1)%3);
                                ImageView imageView=imageList.remove(0);
                                imageList.add(imageView);
                                pageAdapter.notifyDataSetChanged();
                                viewPager.setAdapter(pageAdapter);

                                viewPager.invalidate();


                            }
                        });

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        thread.start();
    }

    //刷新
    private void refreshList() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        init();
                        card.notifyDataSetChanged();
                        refresh.setRefreshing(false);
                        pageAdapter.notifyDataSetChanged();
                    }
                });
            }
        }).start();
    }

    //开启摄像头和从相册中选择相册
    public void doclick(View view){
        switch (view.getId()){

            case R.id.fab:
                Snackbar.make(view,"Data deleted",Snackbar.LENGTH_SHORT).setAction("Undo",new View.OnClickListener(){

                    @Override
                    public void onClick(View v) {
                        Toast.makeText(MainActivity.this,"DtatStore",Toast.LENGTH_SHORT).show();
                    }
                }).show();
                break;

            case R.id.resource1:
                //打开左边的菜单栏
                drawerLayout.openDrawer(relativeLayout);
                break;

            case R.id.image:
                Intent intent1 = new Intent(this, InforActivity.class);
                intent1.putExtra("user",useName);
                startActivity(intent1);
                break;

            case R.id.mess:
                String url="mqqwpa://im/chat?chat_type=wpa&uin=937934445";
                if(isQQAvialable(this)) {
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                }
                break;
            case R.id.exit:
                AlertDialog.Builder builder=new AlertDialog.Builder(MainActivity.this).setTitle("退出当前帐号").setCancelable(false);
                builder.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
                builder.setPositiveButton("exit", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                        System.exit(0);
                    }
                }).show();


                break;
        }
    }

    //判断手机是否已安装QQ
    private boolean isQQAvialable(Context context) {
        PackageManager packageManager=context.getPackageManager();
        List<PackageInfo> l=packageManager.getInstalledPackages(0);
        for(PackageInfo info:l){
            if(info.packageName.equals("com.tencent.mobileqq")){
                return true;
            }
        }
        return false;
    }

    //打开相册
    private void openPicture() {
        Intent intent=new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent,CHOOSE_PHOTO);
    }




    //初始化卡片布局里面的图片，初始化ViewPager里面的图片
    private void init() {
        relativeLayout= (RelativeLayout) findViewById(R.id.start_drawer);
        drawerLayout= (DrawerLayout) findViewById(R.id.drawer_layout);
        Random random=new Random();
        int number=random.nextInt(5)+3;
        for (int i=0;i<number;i++) {
            Information info = new Information(R.drawable.mi, "apple");
            list.add(info);
        }
        int imageView[]=new int[]{R.drawable.about2,R.drawable.background,R.drawable.mi};
        for(int s:imageView) {
            ImageView imageView1 = new ImageView(getApplicationContext());
            imageView1.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView1.setImageResource(s);
            imageList.add(imageView1);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(thread!=null) {
            thread.interrupt();
            thread = null;
        }
    }


    //添加菜单选项，不过必须要在有标题栏的情况下
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main,menu);
        return true;
    }


    /**
     *当侧滑栏是可见的，点击返回键就将侧滑栏的效果关闭掉，但不是整个页面退出；反之则退出整个布局，回到登录界面
     *
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if(keyCode == KeyEvent.KEYCODE_BACK ) {

            if(relativeLayout.getVisibility()==View.VISIBLE){
                //当左边菜单栏是可见的，则关闭
                drawerLayout.closeDrawer(relativeLayout);
//              relativeLayout.setVisibility(View.GONE);

                Log.d("ss","隐藏滑动菜单");
            } else {
                if(!isExit) {
                    isExit=true;
                    Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                }else {
                    isExit=false;
                    moveTaskToBack(true);//实现活动在后台运行
                }
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

}
